package com.spx.core.ui.views;

import java.util.logging.Logger;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.part.ViewPart;

import com.spx.core.CoreActivator;
import com.spx.core.services.ActivityLabel;
import com.spx.core.services.security.AuthorizationException;
import com.spx.core.services.security.AuthorizationUtil;
import com.spx.core.services.security.UnAuthorisedActivityException;
import com.spx.core.types.User;

public abstract class SecureViewPart extends ViewPart
{
	
	protected Logger logger = Logger.getLogger(getClass().getName());
	
	
	
	
	
	final User   getPresentUser(){
	    return 	 CoreActivator.getDefault().getSecurityService().getPresentUser();
	}
	
	

	@Override
	final public void createPartControl(Composite parent)
	{
		try
		{
			securedCreatePartControl(parent);
			if(getClass().getAnnotation(ActivityLabel.class) != null){
				checkActivity();
			}
			
			
		} catch (AuthorizationException ae)
		{
			ae.printStackTrace();
			Shell shell = parent.getShell();
			logger.info("Authorization Failure");
			final Status status = new Status(IStatus.WARNING, CoreActivator.PLUGIN_ID, 0, "Security Error", null);
			ErrorDialog.openError(shell, "Error", "Authorize  Activity", status);
			getViewSite().getPage().hideView(this); 
			this.dispose();
		}
	}

	final public  void checkActivity()
	{
		ActivityLabel annotation = getClass().getAnnotation(ActivityLabel.class);
		if (annotation != null)
		{
			AuthorizationUtil.authorize(getClass());
		}
		
	}

	protected abstract void securedCreatePartControl(Composite parent);

	

}
